window.onLoad = function() {
	init();
}

function init() {
	initMenu();
}

var initMenu = (function() {

	var oMenu = document.getElementsByClassName('menu-wrap')[0],
			oMenuItems = oMenu.getElementsByClassName('main-item'),
			oSub = oMenu.getElementsByClassName('sub')[0],
			oSubItems = oSub.getElementsByClassName('sub-item'),
			oSubLen = oSubItems.length,
			oMenuLen = oMenuItems.length,
			menuItem,
			subItem,
			// 判断鼠标是否进入子菜单标识
			isInSub = false,
			// 定时器
			t = null,
			// 记录鼠标进入菜单的三个坐标
			mousePos = [],
			// 是否是第一次进入
			isFirst = true;

	for(var i = 0; i < oMenuLen; i ++) {
		menuItem = oMenuItems[i];

		addEvent(menuItem, 'mouseenter', menuItemMouseEnter);

		addEvent(oMenu, 'mouseenter', function() {
			addEvent(document, 'mousemove', mouseMove);
		});

		addEvent(oMenu, 'mouseleave', mouseOut);

		addEvent(oSub, 'mouseenter', function() {
			isInSub = true;
		});

		addEvent(oSub, 'mouseleave', function() {
			isInSub = false;
		});
	}

	function menuItemMouseEnter(e) {

		var e = e || window.event,
				tar = e.target || e.srcElement,
				// 获取当前聚焦项的索引
				thisIdx = Array.prototype.indexOf.call(oMenuItems, tar),
				// 倒数第二个坐标
				lastPos = mousePos[mousePos.length - 2] || {x: 0, y: 0},
				// 最后一个坐标
				curPos = mousePos[mousePos.length - 1] || {x: 0, y: 0},
				// 判断是否延时
				toDelay = doTimeout(lastPos, curPos);

		if(t) {
			clearTimeout(t);
		}

		if(!isFirst) {
			if(toDelay) {
				t = setTimeout(function() {
					// 如果鼠标在子菜单中 直接return，不走后续逻辑
					if(isInSub) return;

					// 添加删除聚焦类
					addActive(thisIdx);
				}, 500);
			}else {
				// 添加删除聚焦类
				addActive(thisIdx);	
			}

		}else {
			isFirst = false;
			addActive(thisIdx);
		}

		// 显示右侧页面 去除类名: hide
		oSub.className = 'sub';
		
	}


	function addActive(index) {
		removeAllActive();
		oMenuItems[index].className += ' active';	
		oSubItems[index].className += ' active';	
	}

	function removeAllActive() {
		for(var i = 0; i < oMenuLen; i ++) {
			menuItem = oMenuItems[i];
			menuItem.className = 'main-item';
		}

		for(var i = 0; i < oSubLen; i ++) {
			subItem = oSubItems[i];
			subItem.className = 'sub-item';
		}
	}

	function mouseOut(e) {
		oSub.className += ' hide';
		removeAllActive();
		removeEvent(oMenu, 'mouseleave', mouseMove);
	}

	function mouseMove(e) {
		var e = e || window.event;

		mousePos.push({
			x: pagePos(e).x,
			y: pagePos(e).y
		});

		if(mousePos.length > 3) {
			mousePos.shift();
		}
	}

	// 是否延迟
	function doTimeout(lastPos, curPos) {

		var topLeft = {
			x: getStyles(oMenu, 'width') + getStyles(oMenu, 'margin-left'),
			y: getStyles(oMenu, 'margin-top')
		}

		var bottomLeft = {
			x: getStyles(oMenu, 'width') + getStyles(oMenu, 'margin-left'),
			y: getStyles(oMenu, 'margin-top') + getStyles(oSub, 'height' )
		}

		return pointInTriangle(curPos, lastPos, topLeft, bottomLeft);
	}

})();